package com.itheima.controller;


import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    @GetMapping("/send4Order")
    public Result send4Order(String telephone) throws ClientException {

        String key = telephone+ "_" +  RedisMessageConstant.SENDTYPE_ORDER;
        if (null!=jedisPool.getResource().get(key)){
            return new Result(true, "已经发送了验证码,请注意查收");
        }
        Integer code = ValidateCodeUtils.generateValidateCode(6); //生成一个6位的验证码
        SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());//使用工具生成一个验证码
        jedisPool.getResource().setex(key, 5 * 60, code.toString());//使用Jedis保存
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }


    @PostMapping("/send4Login")
    public Result send4Login(String telephone) throws ClientException {
        String key = telephone+ "_" +  RedisMessageConstant.SENDTYPE_LOGIN;
        if(null!=jedisPool.getResource().get(key)){
            return new Result(false,"验证码已经发送过了,请注意查收");
        }
        Integer code = ValidateCodeUtils.generateValidateCode(6); //生成一个6位的验证码
        SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());//使用工具生成一个验证码
        jedisPool.getResource().setex(key, 5*60, code.toString());//使用Jedis保存
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
